trim() method
This method will allow you to remove all the trailing and leading spaces from the string but it does not remove the middle spaces from the string. This method will check for the space Unicode value from after and before the string and remove it.
Method implementation-
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
Syntax-
public String trim()
Example-
public class Simple{
public static void main(String[] args) {
String s1=" hello";
System.out.println(s1);
String s2=s1.trim();
System.out.println(s2);
}
}
Output-